<template>
  <el-card>
    <el-form>
      <el-form-item label="角色名称">
        <el-input disabled :modelValue="roleName" />
      </el-form-item>
      <el-form-item label="权限列表">
        <el-tree
          class="role-tree"
          :data="permissionList"
          :props="{
            children: 'children',
            label: 'name',
          }"
          show-checkbox
          default-expand-all
          ref="treeRef"
          node-key="id"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="assignRolePermissionList">
          确定
        </el-button>
        <el-button @click="goRole">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "RoleAuth",
};
</script>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import {
  getRolePermissionListApi,
  assignRolePermissionListApi,
} from "@/api/acl/permission";
import type { PermissionList } from "@/api/acl/model/permissionModel";
import { ElMessage } from "element-plus";

const route = useRoute();

const roleName = route.query.roleName as string;

const permissionList = ref<PermissionList>([]);
const treeRef = ref();

onMounted(async () => {
  const res = await getRolePermissionListApi(route.query.id as string);
  permissionList.value = res.children;

  const selectedPermissionList = getSelectPermissionList(res.children);
  // console.log(selectedPermissionList);
  treeRef.value.setCheckedKeys(selectedPermissionList);
});

// 思路：只需要考虑最后一级菜单（父级菜单会根据子菜单选中情况来决定自身的状态）
function getSelectPermissionList(permissionList: PermissionList) {
  let selectedPermissionList: string[] = [];

  permissionList.forEach((permission) => {
    if (permission.children && permission.children.length) {
      // 说明还有子菜单
      const childrenPermissionList = getSelectPermissionList(
        permission.children
      );
      // 将原来数据合并新的子菜单数据，形成一个新数组
      selectedPermissionList = selectedPermissionList.concat(
        childrenPermissionList
      );
      // selectedPermissionList = [
      //   ...selectedPermissionList,
      //   ...childrenPermissionList,
      // ];
      return;
    }

    // 说明没有子菜单
    if (permission.select) {
      selectedPermissionList.push(permission.id);
    }
  });

  return selectedPermissionList;
}
const router = useRouter();

const goRole = () => {
  router.push({
    name: "Role",
  });
};

const assignRolePermissionList = async () => {
  // 获取选中和半选的菜单id
  // console.log(treeRef.value.getCheckedKeys());
  // console.log(treeRef.value.getHalfCheckedKeys());
  await assignRolePermissionListApi(route.query.id as string, [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ]);
  goRole();
  ElMessage.success("分配角色菜单权限成功");
};
</script>

<style scoped>
.role-tree {
  width: 100%;
  text-align: left;
}
</style>
